package gr.nouki.socialparkingfinder;

import gr.nouki.socialparkingfinder.database.DatabaseHelper;
import gr.nouki.socialparkingfinder.database.domain.Driver;

import java.sql.SQLException;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.dao.RuntimeExceptionDao;

public class SignInActivity extends OrmLiteBaseActivity<DatabaseHelper> {

	private final String LOG_TAG = getClass().getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);// Remove title bar
		Log.i(LOG_TAG,
				"creating " + getClass() + " at " + System.currentTimeMillis());

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_sign_in);

		final EditText usernameField = (EditText) findViewById(R.id.usernameText);

		final EditText passwordField = (EditText) findViewById(R.id.passwordText);

		final TextView error = (TextView) findViewById(R.id.errorView);

		error.setVisibility(View.INVISIBLE);

		// signup
		final Button signup = (Button) findViewById(R.id.loginButtonId);
		signup.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					boolean authenticated = authenticate(usernameField
							.getText().toString(), passwordField.getText()
							.toString());

					if (authenticated) {
						error.setText("Authenticated!");
						error.setBackgroundColor(Color.GREEN);
					} else {
						error.setText("Not Authenticated!");
						error.setBackgroundColor(Color.RED);
					}
					error.setVisibility(View.VISIBLE);

				} catch (SQLException e) {
					Log.e(LOG_TAG, e.getMessage(), e);
				}
			}
		});
	}

	private boolean authenticate(String username, String password)
			throws SQLException {

		// get our dao
		RuntimeExceptionDao<Driver, Integer> driverDao = getHelper()
				.getDriverDao();

		GenericRawResults<String[]> rawResults = driverDao
				.queryRaw("select * from driver where username = '" + username
						+ "' and password = '" + password + "'");

		List<Driver> drivers = driverDao.queryBuilder().where()
				.eq("username", username).and().eq("password", password)
				.query();
		if (drivers != null && drivers.size() == 1) {
			return true;
		}

		return false;
	}
}
